<template>
  <div>
    <Category :scene="scene" />

    <el-card style="margin: 10px 0" v-loading="loading">
      <div v-show="scene === 0">
        <el-button :disabled="!categoryStore.c3Id" type="primary" size="default" @click="addAttr" icon="Plus">添加属性</el-button>
        <el-table :data="attrArr" border stripe style="margin: 10px 0">
          <el-table-column label="序号" type="index" width="80" align="center" />
          <el-table-column label="属性名称" width="120" prop="attrName"></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row }">
              <div>
                <el-tag style="margin: 5px" v-for="item in row.attrValueList" type="primary" size="default" effect="dark" :key="item.attrId">{{ item.valueName }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button type="warning" size="small" icon="Edit" @click="updateAttr(row)" />
              <el-popconfirm title="是否确定删除该属性吗？" confirmButtonText="确定" cancelButtonText="取消" @confirm="deleteAttr(row.id)">
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete" />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="scene === 1">
        <!-- 添加或修改属性 -->
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input placeholder="请输入属性名称" v-model="attrParams.attrName" />
          </el-form-item>
        </el-form>

        <el-button :disabled="!attrParams.attrName" type="primary" size="default" icon="Plus" @click="addAttrValue">添加属性值</el-button>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>

        <el-table border style="margin: 10px 0" :data="attrParams.attrValueList">
          <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row, $index }">
              <el-input :ref="(vc: any) => (inputRefs[$index] = vc)" v-if="row.flag" v-model="row.valueName" placeholder="请输入属性值名称" @blur="handleBlur(row, $index)" />
              <div v-else @click="handleEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>

          <el-table-column label="属性值操作">
            <template #default="{ index }">
              <el-button type="warning" size="small" icon="Delete" @click="attrParams.attrValueList.splice(index, 1)" />
            </template>
          </el-table-column>
        </el-table>

        <el-button :disabled="!attrParams.attrValueList.length" type="primary" size="default" icon="Plus" @click="save">保存</el-button>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, reactive, nextTick, onBeforeUnmount } from 'vue'
  import { storeToRefs } from 'pinia'
  import useCategoryStore from '@/store/modules/category'
  import { reqAddOrUpdateAttr, reqAttr, reqRemoveAttr } from '@/api/product/attr/index.ts'
  import type { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type'
  import { getElMessage } from '@/utils/message.ts'

  const categoryStore = useCategoryStore()
  const attrArr = ref<Attr[]>()
  const loading = ref<boolean>(false)
  watch(
    () => categoryStore.c3Id,
    () => {
      attrArr.value = []
      if (!categoryStore.c3Id) return
      getAttr()
    },
  )

  async function getAttr() {
    try {
      const { c1Id, c2Id, c3Id } = storeToRefs(categoryStore)
      loading.value = true
      const res: AttrResponseData = await reqAttr(+c1Id.value, +c2Id.value, +c3Id.value)
      attrArr.value = res.data
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    } finally {
      loading.value = false
    }
  }

  const scene = ref<number>(0)
  const attrParams = reactive<Attr>({
    attrName: '',
    attrValueList: [],
    categoryId: '',
    categoryLevel: 3,
  })
  const inputRefs = ref<any>([])
  // 新增
  function addAttr() {
    Object.assign(attrParams, {
      attrName: '',
      attrValueList: [],
      categoryId: categoryStore.c3Id,
      categoryLevel: 3,
    })
    scene.value = 1
  }

  // 修改
  function updateAttr(row: Attr) {
    scene.value = 1
    Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
  }

  // 删除
  async function deleteAttr(attrId: number) {
    try {
      const res: any = await reqRemoveAttr(attrId)
      if (res.code === 200) {
        getElMessage('删除成功', 'success')
        getAttr()
      } else {
        getElMessage('删除失败', 'error')
      }
    } catch (error) {
      getElMessage((error as Error).message, 'error')
    }
  }

  async function save() {
    const res: any = await reqAddOrUpdateAttr(attrParams)
    if (res.code == 200) {
      scene.value = 0
      getElMessage(attrParams.id ? '修改属性值成功' : '添加属性值成功', 'success')
      getAttr()
    } else {
      getElMessage(attrParams.id ? '修改属性值失败' : '添加属性值失败', 'error')
    }
  }

  function addAttrValue() {
    attrParams.attrValueList.push({
      valueName: '',
      flag: true,
    })
    nextTick(() => {
      inputRefs.value[inputRefs.value.length - 1].focus()
    })
  }

  function handleBlur(row: AttrValue, index: number) {
    if (!row.valueName.trim()) {
      // 删除索引值为空的列表中的数据
      attrParams.attrValueList.splice(index, 1)
      return getElMessage('请输入属性值', 'warning')
    }

    // 属性值不能相同
    let repeat = attrParams.attrValueList.find((item) => {
      // 除去列表中自身元素
      if (item != row) {
        return item.valueName === row.valueName
      }
    })
    if (repeat) {
      attrParams.attrValueList.splice(index, 1)
      return getElMessage('不能输入重复的属性值', 'warning')
    }

    row.flag = false
  }

  function handleEdit(row: AttrValue, index: number) {
    row.flag = true
    nextTick(() => {
      inputRefs.value[index].focus()
    })
  }

  function cancel() {
    scene.value = 0
  }

  onBeforeUnmount(() => {
    // 清空仓库中的数据
    categoryStore.$reset()
  })
</script>

<style lang="scss" scoped></style>
